package com.example.jetpack_viewmodel_livedata

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.jetpack_viewmodel_livedata.sticky.MainActivity1
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
import kotlin.concurrent.timerTask

class MainActivity : AppCompatActivity() {


    lateinit var viewModelProvider: ViewModelProvider
    lateinit var myViewModel: MyViewModel
    lateinit var myLiveDataViewModel: MyLiveDataViewModel
    override fun onRetainCustomNonConfigurationInstance(): Any? {
        return super.onRetainCustomNonConfigurationInstance()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewModelProvider =
            ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(application))
        myViewModel = viewModelProvider.get(MyViewModel::class.java)

        mybtn.setOnClickListener {
            mytv1.text = "${++myViewModel.num}"
        }
        mystartbtn.setOnClickListener {
            startActivity(Intent(this@MainActivity, MainActivity1::class.java))
        }

        mytv1.text = "${myViewModel.num}"

        myLiveDataViewModel = viewModelProvider.get(MyLiveDataViewModel::class.java)

        myLiveDataViewModel.getCurrSecond().observe(this, Observer {
            mytv2.text = "${it}"
        })
        startTimer()

    }

    private fun startTimer() {
        Timer().schedule(timerTask {
            //非ui线程，用postValue
            myLiveDataViewModel.getCurrSecond()
                .postValue(myLiveDataViewModel.getCurrSecond().value?.plus(1))
        }, 1000, 1000)
    }
}